/*
 * @Author: 2112778581 2112778581@qq.com
 * @Date: 2023-10-16 13:04:40
 * @LastEditors: fengshan@0525 3183359488@qq.com
 * @LastEditTime: 2023-11-16 10:47:21
 * @FilePath: \pra\src\category\category.controller.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Category } from '@libs/db/models/category.model';
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Public } from 'src/decorations/public.decorator';
import { CategoryService } from './category.service';

@Controller('category')
export class CategoryController {
  constructor(
    @InjectModel('Category') private readonly categoryModel: Model<Category>,
    private readonly categoryService: CategoryService
  ) { }

  @Post()
  async create(@Body() createCategoryDto: Category) {
    if (createCategoryDto.parent === "") {
      createCategoryDto.parent = null
    }
    const doc = await this.categoryModel.create(createCategoryDto);
    const res = await doc.save();
    return res;
  }

  // 查询所有产品分类
  @Post('/allProdCategory')
  @Public()
  async findAllProdCategory(@Body() createCategoryDto: any) {
    return this.categoryService.findAllProdCategory()
  }


  // 查询所有新闻分类
  @Post('/allNewsCategory')
  @Public()
  async findAllNewsCategory(@Body() createCategoryDto: any) {
    return this.categoryService.findAllNewsCategory()
  }

  /**
   * @breif: 获取产品和新闻分类
   * @return {*}
   */
  @Get('/allCategories')
  @Public()
  getAllCategories() {
    return this.categoryService.getAllCategories()
  }

  @Post('/findAll')
  @Public()
  async findAll(@Body() body: any) {
    let { name, pageNum, pageSize } = body
    pageNum = pageNum || 1
    pageSize = pageSize || 10
    let res = await this.categoryModel.aggregate([
      {
        $match: {
          $or: [
            { 'name': { '$regex': name || '' } }
          ]
        }
      },
      {
        $lookup: {
          from: 'categories',
          localField: 'parent',
          foreignField: '_id',
          as: 'category'
        }
      },
      {
        $facet: {
          total: [{ $count: 'count' }],
          rows: [
            { $skip: (pageNum - 1) * pageSize },
            { $limit: pageSize },
          ],
        },
      },
      {
        $project: {
          list: '$rows',
          total: { $arrayElemAt: ['$total.count', 0] },
        },
      }
    ])
    return res[0]
  }

  @Get(':id')
  @Public()
  findOne(@Param('id') id: string) {
    return this.categoryModel.findById(id).populate({
      path: 'parent',
      populate: { path: 'parent' },
    }).lean()
  }

  @Post(':id')
  async update(@Param('id') id: string, @Body() updateCategoryDto: any) {
    const doc = await this.categoryModel.findByIdAndUpdate(
      id,
      updateCategoryDto,
    );
    const res = await doc.save();
    return res;
  }


  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.categoryModel.deleteOne({ _id: id });
  }
}
